<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "package_transfer".
 *
 * @property string $id
 * @property string $package_id
 * @property integer $transfer
 * @property string $contact
 * @property string $phone
 * @property string $email
 * @property string $address
 * @property integer $method
 * @property string $expected_transfer
 * @property string $wish
 * @property string $detail
 * @property string $updated_at
 * @property integer $lock_user
 * @property string $lock_timestamp
 * @property string $position
 * @property string $remark
 */
class PackageTransfer extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package_transfer';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_id', 'transfer', 'contact', 'phone', 'email', 'address', 'method', 'wish', 'detail', 'position'], 'required'],
            ['email', 'email'],
            [['package_id', 'transfer', 'method', 'lock_user'], 'integer'],
            [['wish', 'detail', 'remark'], 'string'],
            [['updated_at'], 'safe'],
            [['contact', 'phone', 'email', 'address', 'lock_timestamp', 'position'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'package_id' => '资产包',
            'transfer' => '资产包提供方名称', //1持有人、2居间人
            'contact' => '联系人',
            'phone' => '电话',
            'email' => '邮箱',
            'address' => '地址',
            'method' => '转让方式',
            'expected_transfer' => '预计转让时间',
            'wish' => '转让意愿',
            'detail' => '转让价格',
            'updated_at' => '修改时间',
            'lock_user' => '上锁用户',
            'lock_timestamp' => '上锁时间',
            'position' => '职位',
            'remark' => '备注',
        ];
    }

    /*获取转让信息
* * @auth ly
*/
    public function getTransfer($_packageid)
    {
        $transfer = self::find()->where("package_id=$_packageid")->asArray()->all();
        if ($transfer) {
            if (count($transfer) > 1) {//持有人和居间人都有
                $transfer['lumper'] = $transfer[0]['transfer'] == 2 ? $transfer[0] : $transfer[1];
                $transfer['holder'] = $transfer[1]['transfer'] == 1 ? $transfer[1] : $transfer[0];
                unset($transfer[1]);
                unset($transfer[0]);
            }elseif(count($transfer)==1 && $transfer[0]['transfer']==2){//仅有一条数据并且为居间人
                Yii::$app->db->createCommand()->insert(PackageTransfer::tableName(), ['package_id'=>$_packageid,'transfer'=>'1'])->execute();
                $transfer['holder'] = array('transfer' => '1', 'contact' => '', 'phone' => '', 'email' => '', 'address' => '', 'position' => '', 'remark' => '', 'expected_transfer' => '', 'method' => '', 'wish' => '', 'detail' => '');
                $transfer['lumper'] = $transfer[0];
            } else {//仅有一条数据并且是持有人
                $transfer['holder'] = $transfer[0];
                $transfer['lumper'] = array('transfer' => '', 'contact' => '', 'phone' => '', 'email' => '', 'address' => '', 'position' => '', 'remark' => '');
                unset($transfer[0]);
            }
            // $transfer['disTransfer'] = 'disabled="disabled"';
        } else {
//            $transfer['disTransfer'] = '';
            Yii::$app->db->createCommand()->insert(PackageTransfer::tableName(), ['package_id'=>$_packageid,'transfer'=>'1'])->execute();
            $transfer['holder'] = array('transfer' => '', 'contact' => '', 'phone' => '', 'email' => '', 'address' => '', 'position' => '', 'remark' => '', 'expected_transfer' => '', 'method' => '', 'wish' => '', 'detail' => '');
            $transfer['lumper'] = array('transfer' => '', 'contact' => '', 'phone' => '', 'email' => '', 'address' => '', 'position' => '', 'remark' => '');
        }
        return $transfer;
    }

    /**
     * 资产包转让记录
     * @param $id 主键
     * @param $package_id 资产包id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 资类包修改日志module
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public function setUpdateLog($id, $package_id, $changedAttributes, $userId, $module, $type = 2)
    {
        $model = self::findOne((int)$id);
        $package = Package::findOne($package_id);
        if ($model === null || $package === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }
        $attributeLabels = self::attributeLabels();
        $intAttributeLabels = ['package_id', 'transfer', 'method', 'lock_user'];
        $package_transfer = Yii::$app->params['package_transfer'];
        $package_transfer_method = Yii::$app->params['package_transfer_method'];
        $userInfo = (new UserModel())->getDepartmentUsersList(['user.id'=>$userId]);

        switch ($type) {
            //新增
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'package_id':
                                    $value = $package->title;
                                    break;
                                case 'transfer':
                                    $value = $package_transfer[(int)$value];
                                    break;
                                case 'method':
                                    $value = $package_transfer_method[(int)$value];
                                    break;
                                case 'lock_user':
                                    if ($value>0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                default;
                            }
                        }
                        if ($attributeLabels[$key] != 'ID') {
                            $log .= "{$attributeLabels[$key]}：{$value}\n";
                        }
                    }
                }
                break;
            //编辑
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    if ($model->$key != $value) {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {
                    return array('state' => false, 'msg' => '没有做任何修改');
                }

                if (!empty($data)) {
                    $log = '';
                    //$log = '修改ID：' . $id . ',';
                    //$log = '修改ID为' . $id . '的立项信息数据,';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'package_id':
                                    $value = $package->title;
                                    break;
                                case 'transfer':
                                    $value = $package_transfer[(int)$value];
                                    break;
                                case 'method':
                                    $value = $package_transfer_method[(int)$value];
                                    break;
                                case 'lock_user':
                                    if ($value>0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                default;
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;

            //删除
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除记录，";
                break;
            default;
        }

        try {
            $time = date('Y-m-d H:i:s');
            $packageUpdateLog = new PackageUpdateLog();
            $module_title_array = $packageUpdateLog->getModuleArrayTitle();
            $packageUpdateLog->package_id = $package_id;
            $packageUpdateLog->module = $module_title_array[$module];
            $packageUpdateLog->created_at = $time;
            $packageUpdateLog->user_id = $userId;
            $packageUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');

            $re1 = $packageUpdateLog->save();
            if (!$re1) {
                throw new \Exception('资产包转让信息记录添加失败');
            }

            return array('state' => true, 'msg' => '添加资产包转让信息记录成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }

}
